package tm.testing;



import javax.swing.ImageIcon;

import org.lex.input.StrategicHandler;
import org.lex.input.effects.HeightMap;
import org.lex.input.mouse.MouseManager;
import org.lex.input.mouse.component.CombinedMouse;


import com.jme.app.SimpleGame;
import com.jme.bounding.BoundingBox;
import com.jme.image.Texture;
import com.jme.input.MouseInput;
import com.jme.input.MouseInputListener;
import com.jme.intersection.TrianglePickResults;
import com.jme.light.DirectionalLight;
import com.jme.math.Ray;
import com.jme.math.Vector2f;
import com.jme.math.Vector3f;
import com.jme.renderer.ColorRGBA;
import com.jme.renderer.Renderer;
import com.jme.scene.Node;
import com.jme.scene.shape.Box;
import com.jme.scene.state.CullState;
import com.jme.scene.state.FogState;
import com.jme.scene.state.TextureState;
import com.jme.util.TextureManager;
import com.jmex.terrain.TerrainPage;
import com.jmex.terrain.util.ImageBasedHeightMap;

/**
 * <code>TestTerrainPage</code>
 *
 * @author Mark Powell
 * @version $Id: TestTerrainPage.java 4130 2009-03-19 20:04:51Z blaine.dev $
 */
public class SuccessfulPickTest extends SimpleGame implements MouseInputListener {

  private TerrainPage page;
  private Node terrainNode;
  private Node geom;
  private float farPlane = 10000.0f;
  
  private MapGrid mapGrid;
  private int gridSize = 80;
  private int gridElements = 64;
  private TrianglePickResults results;
private StrategicHandler strategicHandler;

  
  

  /**
   * Entry point for the test,
   *
   * @param args
   */
  public static void main(String[] args) {
    SuccessfulPickTest app = new SuccessfulPickTest();
    app.setConfigShowMode(ConfigShowMode.AlwaysShow);
    app.start();
  }

  /**
   * builds the trimesh.
   *
   * @see com.jme.app.SimpleGame#initGame()
   */
  protected void simpleInitGame() {
	  mapGrid = new MapGrid(gridSize, gridElements, rootNode);
	  
	  setupHandler();
	  
	  
	  terrainNode = new Node();
      rootNode.setRenderQueueMode(Renderer.QUEUE_OPAQUE);
     
      
	  DirectionalLight dl = new DirectionalLight();
	  dl.setDiffuse(new ColorRGBA(1.0f, 1.0f, 1.0f, 1.0f));
	  dl.setDirection(new Vector3f(1, -0.5f, 1));
	  dl.setEnabled(true);
	  lightState.attach(dl);
	

	  display.setTitle("Terrain Test");
	  display.getRenderer().setBackgroundColor(new ColorRGBA(0.5f,0.5f,0.5f,1));
	
	  DirectionalLight dr = new DirectionalLight();
	  dr.setEnabled(true);
	  dr.setDiffuse(new ColorRGBA(1.0f, 1.0f, 1.0f, 1.0f));
	  dr.setAmbient(new ColorRGBA(0.5f, 0.5f, 0.5f, 1.0f));
	  dr.setDirection(new Vector3f(0.5f, -0.5f, 0).normalizeLocal());
	
	  CullState cs = display.getRenderer().createCullState();
	  cs.setCullFace(CullState.Face.Back);
	  cs.setEnabled(true);
	  rootNode.setRenderState(cs);
	
	  lightState.attach(dr);
	    
	  ImageIcon image = new ImageIcon(TestOne.class.getClassLoader().getResource("data/textures/testterrain.png"));
	  
	  
	  ImageBasedHeightMap heightMap = new ImageBasedHeightMap(image.getImage());
	  Vector3f terrainScale = new Vector3f(10,1,10);
	  heightMap.setHeightScale( 0.001f);
	  page = new TerrainPage("Terrain", 33, heightMap.getSize(), terrainScale,
			  					heightMap.getHeightMap());
	
	  page.setDetailTexture(1, gridElements);
	  terrainNode.attachChild(page);
	    
	  Texture testgrass = TextureManager.loadTexture(TestOne.class.getClassLoader().
	            getResource(
	                    "data/textures/nicegrass.jpg"),
	                                                        Texture.MinificationFilter.Trilinear,
	                                                        Texture.MagnificationFilter.Bilinear);
	  testgrass.setScale(new Vector3f(90.0f,90.0f,1.0f));
	    
	
	  TextureState ts = display.getRenderer().createTextureState();
	  ts.setEnabled(true);
	
	    
	  ts.setTexture(testgrass, 0);
	  testgrass.setWrap(Texture.WrapMode.Repeat);
	  
	
	  Texture t2 = TextureManager.loadTexture(TestOne.class.getClassLoader().
	                                            getResource(
	        "data/textures/Untitled.png"),
	                                            Texture.MinificationFilter.Trilinear,
	                                            Texture.MagnificationFilter.Bilinear);
	  ts.setTexture(t2, 1);
	  t2.setWrap(Texture.WrapMode.Repeat);
	
	
	  testgrass.setApply(Texture.ApplyMode.Combine);
	  testgrass.setCombineFuncRGB(Texture.CombinerFunctionRGB.Modulate);
	  testgrass.setCombineSrc0RGB(Texture.CombinerSource.CurrentTexture);
	  testgrass.setCombineOp0RGB(Texture.CombinerOperandRGB.SourceColor);
	  testgrass.setCombineSrc1RGB(Texture.CombinerSource.PrimaryColor);
	  testgrass.setCombineOp1RGB(Texture.CombinerOperandRGB.SourceColor);
	  
	
	  t2.setApply(Texture.ApplyMode.Combine);
	  t2.setCombineFuncRGB(Texture.CombinerFunctionRGB.AddSigned);
	  t2.setCombineSrc0RGB(Texture.CombinerSource.CurrentTexture);
	  t2.setCombineOp0RGB(Texture.CombinerOperandRGB.SourceColor);
	  t2.setCombineSrc1RGB(Texture.CombinerSource.Previous);
	  t2.setCombineOp1RGB(Texture.CombinerOperandRGB.SourceColor);
	  terrainNode.setRenderState(ts);
	
	  geom = new Node();
	  
	  FogState fogState = display.getRenderer().createFogState();
	  fogState.setDensity(1.0f);
	  fogState.setEnabled(true);
	  fogState.setColor(new ColorRGBA(1.0f, 1.0f, 1.0f, 1.0f));
	  fogState.setEnd(farPlane);
	  fogState.setStart(farPlane / 10.0f);
	  fogState.setDensityFunction(FogState.DensityFunction.Linear);
	  fogState.setQuality(FogState.Quality.PerVertex);
	  terrainNode.setRenderState(fogState);
	  rootNode.attachChild(terrainNode);
	    
	  
	  try {
		Box box = new Box("BOX1?", mapGrid.getElementCoord(32,32,132), 10, 10, 10);
		box.setModelBound(new BoundingBox());
		box.updateModelBound();
		
		geom.attachChild(box);
		rootNode.attachChild(geom);
		
	} catch (MapElementIndexOutOfBoundsException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
  }
  
  
	public void setupHandler() {
		HeightMap heightMap = new HeightMap() {
			public float getHeightAt(Vector3f location) {
				float height = 250;
				if (Float.isNaN(height)) height = 0;
				return height;
			}
		};
		MouseManager mouseManager = new MouseManager(CombinedMouse.get());

		strategicHandler = new StrategicHandler(
				cam, mouseManager, heightMap);
		input = strategicHandler;
		
		mouseManager.registerWithInputHandler(strategicHandler);
		mouseManager.addListener(this);
		mouseManager.setMousePosition(
			display.getWidth()/2, display.getHeight()/2);
		statNode.attachChild(mouseManager.getMouse().getMouseSpatial());
		
		mouseManager.setNativeMousePreferred(true);
		mouseManager.getMouse().setCursorVisible(true);
		update(0);
		mouseManager.setNativeMousePreferred(false);
		
		
	}

  
  
  protected void simpleUpdate() {
	  strategicHandler.useCursor("default");
  }
  
  
  protected void cameraPerspective() {
      cam.setFrustumPerspective( 60.0f, (float) display.getWidth() / (float) display.getHeight(), 1, 3500 );
      cam.setParallelProjection( false );
      cam.update();
  }
  

  
	private void processPick(int x, int y) {
		System.out.println("PICK!");
    		
    	//mouseState.setMousePosition(new Coordinate(mouse_x, mouse_y));
    		
    	Vector2f screenPos = new Vector2f();
    	//Get the position that the mouse is pointing to
    	
		screenPos.set(x, y);
		System.out.println(screenPos.x + "AHA "+ screenPos.y);
		// Get the world location of that X,Y value
		Vector3f worldCoords = display.getWorldCoordinates(screenPos, 1.0f);
		// Create a ray starting from the camera, and going in the direction
        // of the mouse's location
        final Ray mouseRay = new Ray(cam.getLocation(), worldCoords
                .subtractLocal(cam.getLocation()));
        mouseRay.getDirection().normalizeLocal();
        results = new TrianglePickResults();
        results.clear();
        results.setCheckDistance(true);
        geom.findPick(mouseRay,results);
        

        
    	if(results.getNumber() > 0) {
    		System.out.println("VORHER: "+results.getNumber()+" AHA: "+results.getPickData(0).getTargetMesh().getName());
    		/**
	    	Vehicle tmp = Vehicle.getVehicleBySpatialName(vehicleList, results.getPickData(0).getTargetMesh().getName());
	    	System.out.println(tmp.getId());
	    	if(tmp.getMotionState()==Vehicle.DRIVING) {
	    		tmp.setMotionState(Vehicle.IDLE);
	    	} else if (tmp.getMotionState()==Vehicle.IDLE) {
	    		tmp.setMotionState(Vehicle.DRIVING);
	    	}
	    	*/
    	}
    	
	}

	
	public void onButton(int button, boolean pressed, int x, int y) {
		if(button==0 && pressed ==false)
		processPick(x,y);
	}

	public void onMove(int xDelta, int yDelta, int newX, int newY) {
		// TODO Auto-generated method stub
		
	}

	public void onWheel(int wheelDelta, int x, int y) {
		// TODO Auto-generated method stub
		
	}

  
  
}


